﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace YaAppoint.OnlineServiceCache
{
    public class OnlineServiceCache
    {
        private static readonly ConcurrentDictionary<Guid, OnlineServieCacheItem<OnlineService>> _onLineServices
                = new ConcurrentDictionary<Guid, OnlineServieCacheItem<OnlineService>>();


        // 定时清理任务
        private static readonly Timer _cleanupTimer;
        private static readonly TimeSpan _cleanupInterval = TimeSpan.FromMinutes(5);

        static OnlineServiceCache()
        { 
            
        }


        /// <summary>
        /// 获取GUI对应的OnlineService
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static OnlineService Get(Guid key)
        {
            if (_onLineServices.TryGetValue(key, out var cacheItem))
            {
                if (!cacheItem.IsExpired)
                {
                    return cacheItem.Value;
                }
                else
                {
                    // 已过期
                    _onLineServices.TryRemove(key,out _);
                }
            }
            return null;
        }

        // 设置缓存
        public static void Set(Guid key, OnlineService value, TimeSpan? expiration = null)
        {
            var cacheItem = new OnlineServieCacheItem<OnlineService>(value, expiration);
            _onLineServices.AddOrUpdate(key, cacheItem, (k, existing) => cacheItem);
        }

        // 移除指定缓存
        public static bool Remove(Guid key)
        {
            return _onLineServices.TryRemove(key, out _);
        }

        // 检查缓存是否存在且未过期
        public static bool Contains(Guid key)
        {
            if (_onLineServices.TryGetValue(key, out var cacheItem))
            {
                if (!cacheItem.IsExpired)
                {
                    return true;
                }
                else
                {
                    _onLineServices.TryRemove(key, out _);
                }
            }
            return false;
        }

        // 获取所有缓存健
        public static List<Guid> GetAllKeys()
        {
            CleanUpExpiredItems(); // 清理过期缓存
            return _onLineServices.Keys.ToList();
        }

        // 清理所有缓存
        public static void Clear()
        {
            _onLineServices.Clear();
        }

        // 清理过期缓存
        private static void CleanUpExpiredItems(object state = null)
        { 
            var expireKeys = _onLineServices.Where(pair=>pair.Value.IsExpired)
                                            .Select(pair=>pair.Key)
                                            .ToList();
            foreach (var key in expireKeys)
            {
                _onLineServices.TryRemove(key, out _);
            }
        }
    }
}
